package com.qf.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.DtsStorageMapper;
import com.qf.pojo.DtsStorage;
import com.qf.service.DtsStorageService;
import com.qf.util.AliyunOSSUtil;
import com.qf.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class DtsStorageServiceImpl implements DtsStorageService {
    @Autowired
    DtsStorageMapper storageMapper;
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;
    @Override
    public DtsStorage save(DtsStorage file, byte[] bus) throws Exception {
        //上传到阿里云OSS
        //获取唯一的key
        String uuid = UUID.randomUUID().toString();
        String key = uuid + file.getName();
        //文件的访问连接：上传成功后，自动获取
        String url = AliyunOSSUtil.uploadImage(endpoint,accessKeyId,accessKeySecret,bucketName,key,bus);
        file.setKey(key);
        file.setUrl(url);
        //保存信息到数据库
        file.setAddTime(new Date());
        file.setUpdateTime(new Date());
        file.setDeleted(false);
        storageMapper.insert(file);
        return file;
    }

    @Override
    public Map<String, Object> queryPage(Integer page, Integer limit, String name, String key, String sort, String order) {
        IPage<DtsStorage> ipage = new Page<>(page,limit);
        QueryWrapper<DtsStorage> wrapper = new QueryWrapper<>();
        //
        if(!StringUtils.isEmpty(name)) {
            wrapper.like("name", name);
        }
        if(!StringUtils.isEmpty(key)) {
            wrapper.like("`key`", key);
        }
        if(!StringUtils.isEmpty(sort) && StringUtils.isEmpty(order) ) {
            if("desc".equals(order)){
                wrapper.orderByDesc(sort);
            }else{
                wrapper.orderByAsc(sort);
            }
        }
        storageMapper.selectPage(ipage, wrapper);

        Map<String,Object> data = new HashMap<>();
        data.put("items", ipage.getRecords());
        data.put("total", ipage.getTotal());

        return data;
    }
}
